package me.zhangsanfeng.gpss.common.handler;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import me.zhangsanfeng.gpss.common.entity.JwtProperty;
import me.zhangsanfeng.gpss.common.utils.*;
import me.zhangsanfeng.gpss.dao.UsersRepository;
import me.zhangsanfeng.gpss.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登出成功处理器
 */
@Slf4j
@Component
public class LogoutOverHandler implements LogoutSuccessHandler {

    private static LogoutOverHandler logoutOverHandler;

    @Autowired
    private UsersRepository repository;

    @PostConstruct
    public void init(){
        logoutOverHandler=this;
        logoutOverHandler.repository=this.repository;
    }

    private JwtProperty jwtProperty;

    public LogoutOverHandler(JwtProperty jwtProperty){
        this.jwtProperty = jwtProperty;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request,
                                HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {

        response.setContentType("application/json;charset=UTF-8");
        //通过token解析出封装的授权信息
        String auth = request.getHeader("Authorization");
        if (DataUtil.isNotEmpty(auth)){
            response.addHeader("Authorization",null);
        }

        Claims claims = null;
        try {
            claims = JwtUtil.parseToken(auth.replace("Bearer ", ""),
                    jwtProperty.getBase64Security());
        } catch (Exception e) {
            response.getWriter().write(JsonUtil.toJsonString(ResultUtil.error(e)));
            return;
        }
        String username = claims.get("username").toString();

        /*jpa审计：自动更新insert_by、update_by等字段，需要从SecurityContextHolder中取出当前用户信息
        用户注销后，SecurityContextHolder.Context被清空，需要将authentication存入SecurityContextHolder中
         */
        SecurityContextHolder.getContext().setAuthentication(authentication);

        //记录登出时间
        Users user = null;
        if (DataUtil.isNotEmpty(claims)){
            user = repository.findByUsername(username);
            user.setLogoutTime(DateUtil.currentTimestamp());
            user.setOnlineTime(user.getLogoutTime().getTime()-user.getLoginTime().getTime());
        }
        Users flush = repository.saveAndFlush(user);

        //SecurityContextHolder.getContext().setAuthentication(null);
        //在线时长
        Long onlineTime = flush.getOnlineTime();



       //封装返回值
        Map<String,String> map = new HashMap<>();
        map.put("Username",flush.getUsername());
        map.put("loginIp",flush.getIpAddr());
        map.put("loginTime",DateUtil.date2String(flush.getLoginTime(),
                DateUtil.DATE_PATTERN.YYYY_MM_DD_HH_MM_SS));
        map.put("logoutTime",DateUtil.date2String(flush.getLogoutTime(),
                DateUtil.DATE_PATTERN.YYYY_MM_DD_HH_MM_SS));
        map.put("onlineTime",DateUtil.dateDiff(onlineTime));
        response.getWriter().write(JsonUtil.toJsonString(ResultUtil.success(map)));

    }

}
